<template>
  <section class="main">
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="checkAll"
    />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <li
        :class="{ completed: item.isDone, editing: storeId === item.id }"
        v-for="item in showList"
        :key="item.id"
      >
        <div class="view">
          <!-- 
            checked与v-model的区别
            v-model: 双向数据绑定
            checked: 只会影响默认是否选中
           -->
          <input
            class="toggle"
            type="checkbox"
            :checked="item.isDone"
            @change="change(item.id)"
          />
          <label @dblclick="showipt(item)">{{ item.name }}</label>
          <button class="destroy" @click="del(item.id)"></button>
        </div>
        <input
          class="edit"
          value="Create a TodoMVC template"
          v-model="storeName"
          @keyup.enter="revamp"
          @keyup.esc="cancel"
        />
      </li>
    </ul>
  </section>
</template>

<script>
export default {
  data() {
    return {
      storeId: '',
      storeName: '',
    }
  },
  props: {
    list: {
      type: Array,
      required: true,
    },
    type: {
      type: String,
      required: true,
    },
  },
  methods: {
    del(id) {
      // console.log('删除任务', id)
      this.$emit('del', id)
    },
    change(id) {
      // console.log('改变状态', id)
      this.$emit('change', id)
    },
    showipt(item) {
      // console.log('拿到了双击的id', item.id)
      this.storeId = item.id
      this.storeName = item.name
    },
    revamp() {
      if (!this.storeName) {
        return alert('请输入修改后的任务名')
      }
      this.$emit('revamp', this.storeName, this.storeId)
      this.storeId = ''
      this.storeName = ''
    },
    cancel() {
      this.storeId = ''
      this.storeName = ''
    },
  },
  computed: {
    showList() {
      if (this.type === 'active') {
        return this.list.filter(item => !item.isDone)
      } else if (this.type === 'completed') {
        return this.list.filter(item => item.isDone)
      } else {
        return this.list
      }
    },
    checkAll: {
      get() {
        return this.list.every(item => item.isDone)
      },
      set(value) {
        this.$emit('checkAll', value)
        // this.list.forEach(item => (item.isDone = value))
      },
    },
  },
}
</script>

<style></style>
